package com.example.myapplication.loginandregister;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.method.TransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.example.database.mysql.userdb.User;
import com.example.database.mysql.userdb.UserDBService;
import com.example.myapplication.R;
import com.example.myapplication.databinding.ActivityRegisterBinding;
import com.mob.MobSDK;

import java.text.SimpleDateFormat;
import java.util.Date;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class RegisterActivity extends AppCompatActivity {
    private ActivityRegisterBinding binding;
    private boolean isHideFirst = false; // 输入框密码是否隐藏的，默认为true
    private boolean isHideFirst2 = false; // 输入框确认密码是否隐藏的，默认为true

    String APPKEY = "324fe44a3c900";
    String APPSECRETE = "d94d6e3819e37a668fff3e531b87f5ca";

    // 倒计时
    int i = 30;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_register);
        init();
        initListener();
        cliclk();
    }

    private void init() {
        // 启动短信验证sdk
        MobSDK.init(this, APPKEY, APPSECRETE);
        EventHandler eventHandler = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }
        };
        //注册回调监听接口
        SMSSDK.registerEventHandler(eventHandler);
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == -9) {
                binding.textView29.setText("重新发送(" + i + ")");
            } else if (msg.what == -8) {
                binding.textView29.setText("获取验证码");
                binding.imageView29.setClickable(true);
                i = 30;
            } else {
                int event = msg.arg1;
                int result = msg.arg2;
                Object data = msg.obj;
                Log.e("event", "event=" + event);
                if (result == SMSSDK.RESULT_COMPLETE) {
                    // 短信注册成功后，返回MainActivity,然后提示
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {// 提交验证码成功
                        Toast.makeText(RegisterActivity.this, "注册 成功",
                                Toast.LENGTH_SHORT).show();
                        RegisterActivity.this.finish();
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        Toast.makeText(RegisterActivity.this, "正在获取验证码",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        ((Throwable) data).printStackTrace();
                    }
                }else {
                    Toast.makeText(RegisterActivity.this, "验证码错误",
                            Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    // 为文本框设置监听器
    private void initListener() {
        binding.editText0.addTextChangedListener(textWatcher);
        binding.editText2.addTextChangedListener(textWatcher);
        binding.editText3.addTextChangedListener(textWatcher);
        binding.editText5.addTextChangedListener(textWatcher);
        binding.editText4.addTextChangedListener(textWatcher);
        binding.imageView33.setImageResource(R.drawable.see);
        binding.imageView27.setImageResource(R.drawable.see);
    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (binding.editText0.getEditableText().length() >= 1) {
                binding.imageView0.setVisibility(View.VISIBLE);
            }else {
                binding.imageView0.setVisibility(View.GONE);
            }
            if (binding.editText2.getEditableText().length() >= 1) {
                binding.imageView28.setVisibility(View.VISIBLE);
            }else {
                binding.imageView28.setVisibility(View.GONE);
            }
            if (binding.editText3.getEditableText().length() >= 1) {
                binding.imageView30.setVisibility(View.VISIBLE);
            }else {
                binding.imageView30.setVisibility(View.GONE);
            }
            if (binding.editText5.getEditableText().length() >= 1) {
                binding.imageView34.setVisibility(View.VISIBLE);
            }else {
                binding.imageView34.setVisibility(View.GONE);
            }
            if (binding.editText4.getEditableText().length() >= 1) {
                binding.imageView32.setVisibility(View.VISIBLE);
            }else {
                binding.imageView32.setVisibility(View.GONE);
            }
        }
    };

    public void cliclk() {

        // 返回登录界面
        binding.imageView26.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RegisterActivity.this.finish();
            }
        });

        // 切换到登录界面
        binding.textView15.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RegisterActivity.this.finish();
            }
        });

        // 清空各个输入框
        binding.imageView0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.editText0.setText("");
            }
        });
        binding.imageView28.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.editText2.setText("");
            }
        });
        binding.imageView30.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.editText3.setText("");
            }
        });
        binding.imageView34.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.editText5.setText("");
            }
        });
        binding.imageView32.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.editText4.setText("");
            }
        });
        // 设置密码可见与不可见
        binding.imageView33.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isHideFirst) {
                    binding.imageView33.setImageResource(R.drawable.see);
                    //密文
                    TransformationMethod method = PasswordTransformationMethod.getInstance();
                    binding.editText5.setTransformationMethod(method);
                    isHideFirst = false;
                }else {
                    binding.imageView33.setImageResource(R.drawable.notsee);
                    // 密文
                    HideReturnsTransformationMethod method1 = HideReturnsTransformationMethod.getInstance();
                    binding.editText5.setTransformationMethod(method1);
                    isHideFirst = true;
                }
                // 光标的位置
                int index = binding.editText5.getText().toString().length();
                binding.editText5.setSelection(index);
            }
        });
        // 设置确认密码可见与不可见
        binding.imageView27.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isHideFirst2) {
                    binding.imageView27.setImageResource(R.drawable.see);
                    //密文
                    TransformationMethod method = PasswordTransformationMethod.getInstance();
                    binding.editText4.setTransformationMethod(method);
                    isHideFirst2 = false;
                }else {
                    binding.imageView27.setImageResource(R.drawable.notsee);
                    // 密文
                    HideReturnsTransformationMethod method1 = HideReturnsTransformationMethod.getInstance();
                    binding.editText4.setTransformationMethod(method1);
                    isHideFirst2 = true;
                }
                // 光标的位置
                int index = binding.editText4.getText().toString().length();
                binding.editText4.setSelection(index);
            }
        });

        //注册
        binding.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //获取输入的手机号码
                String phoneNumbers = binding.editText2.getText().toString();

                if (binding.editText0.getEditableText().length() == 0) {
                    Toast.makeText(RegisterActivity.this, "昵称不能为空", Toast.LENGTH_LONG).show();
                }else if (binding.editText2.getEditableText().length() == 0) {
                    Toast.makeText(RegisterActivity.this, "手机号码不能为空", Toast.LENGTH_LONG).show();
                }else if (binding.editText3.getEditableText().length() == 0) {
                    Toast.makeText(RegisterActivity.this, "验证码不能为空", Toast.LENGTH_LONG).show();
                }else if (binding.editText4.getEditableText().length() == 0 || binding.editText5.getEditableText().length() == 0) {
                    Toast.makeText(RegisterActivity.this, "密码不能为空", Toast.LENGTH_LONG).show();
                }else if (!binding.editText4.getText().toString().equals(binding.editText5.getText().toString())) {
                    Toast.makeText(RegisterActivity.this, "两次密码不一致", Toast.LENGTH_LONG).show();
                }else {
                    Observable.create(new ObservableOnSubscribe<Integer>() {
                        @Override
                        public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Exception {
                            UserDBService dbService = UserDBService.getDbService();
                            User user = new User();
                            user.setPhoneNumber(binding.editText2.getText().toString());
                            user.setPassWord(binding.editText5.getText().toString());
                            user.setNickName(binding.editText0.getText().toString());
                            user.setPhoto("");
                            user.setSex("");
                            user.setDateOfBirth("");
                            user.setPersonalSignature("");
                            user.setIsVolunteers(2);
                            SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd ' ' HH:mm:ss z");
                            Date date = new Date(System.currentTimeMillis());
                            System.out.println(formatter.format(date));
                            user.setRegistrationTime(String.valueOf(date));
                            Log.d("user",user.toString());
                            Integer result = (Integer) dbService.addUser(user);
                            System.out.println(result);
                            emitter.onNext(result);
                        }
                    })
                    .observeOn(Schedulers.io())   //为上面代码分配io线程
                    .subscribeOn(AndroidSchedulers.mainThread())   //为下面的代码分配主线程
                    .subscribe(new Consumer<Integer>() {
                        @Override
                        public void accept(Integer integer) throws Exception {
                            if (integer > 0) {
                                SMSSDK.submitVerificationCode("86",phoneNumbers,binding.editText3.getText().toString());
                                Toast.makeText(RegisterActivity.this, "注册成功!", Toast.LENGTH_SHORT).show();
                            }else {
                                Toast.makeText(RegisterActivity.this, "注册失败!", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
            }
        });

        //获取验证码
        binding.imageView29.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //获取输入的手机号码
                String phoneNumbers = binding.editText2.getText().toString();

                //1,通过规则判断手机号
                if (!judgePhoneNums(phoneNumbers)) {
                    return;
                }
                //2,通过sdk发送短信验证
                SMSSDK.getVerificationCode("86",phoneNumbers);

                //3,把按钮变成不可点击，并且显示倒计时(正在获取)
                binding.imageView29.setClickable(false);
                binding.textView29.setText("重新发送(" + i + ")");

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (; i > 0; i--) {
                            handler.sendEmptyMessage(-9);
                            if (i <= 0) {
                                break;
                            }
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        handler.sendEmptyMessage(-8);
                    }
                }).start();
            }
        });
    }

    /**
    * 验证手机号码
    */
    private boolean judgePhoneNums(String phoneNums) {
        if (isMatchLength(phoneNums,11)
                 && isMobileNo(phoneNums)) {
            return true;
        }
        Toast.makeText(this,"手机号码输入有误！", Toast.LENGTH_SHORT).show();
        return false;
    }

    /**
    * 验证手机号码长度
    */
    public static boolean isMatchLength(String str, int length) {
        if (str.isEmpty()) {
            return false;
        }else {
            return str.length() == length ? true : false;
        }
    }

    /**
    * 验证是否是手机号码
    */
    public static boolean isMobileNo(String mobileNums) {
        /*
         * 移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
         * 联通：130、131、132、152、155、156、185、186 电信：133、153、180、189、（1349卫通）
         * 总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
         */
        String telRegex = "[1][358]\\d{9}";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobileNums)) {
            return false;
        }else {
            return mobileNums.matches(telRegex);
        }
    }

    @Override
    protected void onDestroy() {
        SMSSDK.unregisterAllEventHandler();
        super.onDestroy();
    }
}